//
//  SwitchViewController.m
//  iPhone SRV
//
//  Created by Nick Kitchener on 06/07/2009.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "RootViewController.h"
#import "ConnectionViewController.h"
#import "ImmediateViewController.h"
#import "MappedViewController.h"
#import "SRVBlackfin.h"

@implementation RootViewController
@synthesize connectionViewController;
@synthesize immediateViewController;
@synthesize mappedViewController;
//@synthesize menuViewController;
@synthesize srv;

//===========================================================================================================
// Root

 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
	}
	return self;
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	NSLog(@"view did load");
	NSLog(@"connection view init");
	connectionViewController = [[ConnectionViewController alloc] initWithNibName:@"ConnectionViewController" bundle:nil];
//	[self.view addSubview:connectionViewController];
	//		[connectionViewController release];
	
	// start probe & connect
	[self startProbe];
	
	// by doing this the SRV blackfin connections are being initialised
	srv = [[SRVController alloc]init];
	[[srv uart0] setConnectionStateListener:self];
	[[srv uart1] setConnectionStateListener:self];
	
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}

- (void)dealloc {
    [super dealloc];
}

- (void)viewWillAppear:(BOOL)animated {
}

- (void)viewWillDisappear:(BOOL)animated {
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
	[immediateViewController willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
}

NSString *kIPAddressKey = @"srv_ip_address";
NSString *kPortNumberUART0Key = @"uart0_port_number";
NSString *kPortNumberUART1Key = @"uart1_port_number";

-(void)loadApplicationPreferences {
	prefIPAddress		= [[NSUserDefaults standardUserDefaults] stringForKey:kIPAddressKey];
	prefPortNumberUART0 = [[NSUserDefaults standardUserDefaults] integerForKey:kPortNumberUART0Key];
	prefPortNumberUART1 = [[NSUserDefaults standardUserDefaults] integerForKey:kPortNumberUART1Key];
	NSLog(@"application preferences: IP=%@, a=%i, b=%i", prefIPAddress, prefPortNumberUART0, prefPortNumberUART1);
}

//===========================================================================================================
// Probing..

-(void)startProbe {
	// set the view to connection
	NSLog(@"startProbe");
//	[self.view bringSubviewToFr*ont:connectionViewController.view];	
	[[srv uart0] disconnect];
	[[srv uart1] disconnect];
	
	[connectionViewController setMatchPort:NO];
	[connectionViewController setBlackfinUART0:NO];
	[connectionViewController setBlackfinUART1:NO];
	
	// set an expiry timer
	[NSTimer scheduledTimerWithTimeInterval:5.0
									 target:self
								   selector:@selector(probeExpired:)
								   userInfo:nil
									repeats:NO];	
}

// probe expired
- (void)probeExpired:(NSTimer*)theTimer {
	// match port failed then we don't have any connectivity.
	// one or two blackfins - we're ok.
	[self showImmediate];
}

-(void)initialisationComplete:(id<SRVBlackfin>)sender {
	if( sender == [srv uart0] ) {
		[[srv uart0] connectToURL:prefIPAddress port:prefPortNumberUART0];
	} else {
		[[srv uart1] connectToURL:prefIPAddress port:prefPortNumberUART1];
	}
}

// blackfin has become available
- (void) blackfinAvailable:(id)sender {
	if( sender == [srv uart0] ) {
		[connectionViewController setBlackfinUART0:YES];
	} else {
		[connectionViewController setBlackfinUART1:YES];
	}
}

// blackfin initially or has become unavailable
- (void) blackfinUnavailable:(id)sender {
	if( sender == [srv uart0] ) {
		[connectionViewController setBlackfinUART0:NO];
	} else {
		[connectionViewController setBlackfinUART1:NO];
	}
}

-(void)connectComplete:(id<SRVBlackfin>)sender {	
	// ok we know the Matchport is working 
	[connectionViewController setMatchPort:YES];
}

-(void)connectionError:(id)sender {
	NSLog(@"iPhoneSRV: Connection error occured %@", sender);
}

-(void)disconnectComplete:(id)sender {
}



-(void)showMenu {
/*	MenuViewController *menuController = [[MenuViewController alloc] initWithNibName:@"MenuViewController" bundle:nil];
	menuViewController = menuController;
	[self.view addSubview:menuController.view];
	[menuController release];*/
}

-(void)showImmediate {
	ImmediateViewController *immediateController = [[ImmediateViewController alloc] initWithNibName:@"ImmediateViewController" bundle:nil];
	immediateViewController = immediateController;
	[[immediateViewController cameraViewUART0] setBlackfin:[srv uart0]];
	[[immediateViewController cameraViewUART1] setBlackfin:[srv uart1]];	
	[immediateController viewWillAppear:NO];
	[self.view addSubview:immediateController.view];
	[self.view bringSubviewToFront:immediateController.view];
}

-(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {
	[immediateViewController.joypad touchesBegan:touches withEvent:event];
}
-(void)touchesEnded:(NSSet*)touches withEvent:(UIEvent*)event {
	[immediateViewController.joypad touchesEnded:touches withEvent:event];
}
-(void)touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {
	[immediateViewController.joypad touchesMoved:touches withEvent:event];}
-(void)touchesCancelled:(NSSet*)touches withEvent:(UIEvent*)event {
	[immediateViewController.joypad touchesCancelled:touches withEvent:event];}

@end




